package com.atguigu.gulimall.product.controller;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 商品三级分类
 *
 * @author LiQianJin
 * @email 18410584912@qq.com
 * @date 2024-03-23 17:56:12
 */
@RestController
@RequestMapping("product/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    // 获取三级分类信息--以树形结构展示
    @RequestMapping("/list/tree")
    public R listWithTree() {
        List<CategoryEntity> entityList = categoryService.listWithTree();
        return R.ok().put("data", entityList);
    }

    // 批量删除分类
    @PostMapping("/batchRemove")
    public R batchRemove(@RequestBody List<Long> idList) {
        try {
            if (log.isInfoEnabled()) {
                log.info("CategoryController.batchRemove.dto:{}", JSON.toJSONString(idList));
            }
            // 批量删除操作
            Preconditions.checkArgument(!CollectionUtils.isEmpty(idList), "分类ID不能为空");
            Integer count = categoryService.batchRemove(idList);
            return R.ok().put("删除成功", String.valueOf(count));
        } catch (Exception e) {
            log.info("CategoryController.batchRemove.error:{}", e, e.getMessage());
            return R.error(e.getMessage());
        }

    }

    /**
     * 信息
     */
    @RequestMapping("/info/{catId}")
    public R info(@PathVariable("catId") Long catId) {
        CategoryEntity category = categoryService.getById(catId);

        return R.ok().put("category", category);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody CategoryEntity category) {
        categoryService.save(category);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody CategoryEntity category) {
        categoryService.updateById(category);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] catIds) {
        categoryService.removeByIds(Arrays.asList(catIds));

        return R.ok();
    }

}
